﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nb.Common.Configurations
{
    public class ConfigHelper
    {
        /// <summary>
        /// 如果为空，返回defaultValueIfNull
        /// </summary>
        /// <param name="key"></param>
        /// <param name="defaultValueIfNull"></param>
        /// <returns></returns>
        public static string GetAppSettingValue(string key, string defaultValueIfNull = null)
        {
            string result = defaultValueIfNull;
            //如果后台有设置，以config的设置为准
            string settingValue = ConfigurationManager.AppSettings[key];
            if (!string.IsNullOrWhiteSpace(settingValue))
            {
                result = settingValue;
            }
            return result;
        }

        /// <summary>
        /// 如果为空，返回false
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool GetAppSettingValueOfBoolean(string key)
        {
            bool value = false;
            //如果后台有设置，以config的设置为准
            string valueSetting = ConfigurationManager.AppSettings[key];
            if (!string.IsNullOrWhiteSpace(valueSetting) && valueSetting.Trim().Equals("true", StringComparison.OrdinalIgnoreCase))
            {
                value = true;
            }

            Log(string.Format("GetBoolValue From AppSettings invoke at {0}, {1} = {2} => \r\n", DateTime.Now, key, value));
            return value;
        }

        /// <summary>
        /// 如果为空，返回默认defaultValueIfNull
        /// </summary>
        /// <param name="key"></param>
        /// <param name="defaultValueIfNull"></param>
        /// <returns></returns>
        public static int GetAppSettingValueOfInt(string key, int defaultValueIfNull)
        {
            int value = defaultValueIfNull;
            //如果后台有设置，以config的设置为准
            string valueSetting = ConfigurationManager.AppSettings[key];
            if (!string.IsNullOrWhiteSpace(valueSetting))
            {
                value = int.Parse(valueSetting);
            }

            Log(string.Format("GetIntValue From AppSettings invoke at {0}, {1} = {2} => \r\n", DateTime.Now, key, value));
            return value;
        }

        private static void Log(string message)
        {
            UtilsLogger.LogMessage(message);
        }
    }
}
